package com.itheima.reggie.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.Redisks;
import com.itheima.reggie.dto.LoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SendSms;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @author lifeihu
 * @date 2021/11/27
 * @TIME:18:01
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpServletRequest req){
        Integer code = ValidateCodeUtils.generateValidateCode(6);
//        SendSms.sendMsg(user.getPhone(),code+"");
        System.out.println(code);
        HttpSession session = req.getSession();
//        session.setAttribute(user.getPhone(),code+"");
        redisTemplate.opsForValue().set(Redisks.REDIS_CODE+user.getPhone(),code+"",5,TimeUnit.MINUTES);
        return R.success("发送验证码成功");
    }
    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto,HttpServletRequest req){
        //1). 获取前端传递的手机号和验证码
        if(loginDto==null){
            return R.error("参数异常");
        }
        //2). 从Session中获取到手机号对应的正确的验证码
        HttpSession session = req.getSession();
//       String code = (String) session.getAttribute(loginDto.getPhone());
        String code = (String) redisTemplate.opsForValue().get(Redisks.REDIS_CODE + loginDto.getPhone());
        if(null==code||code==""){
            return R.error("请获取验证码");
        }
        //3). 进行验证码的比对 , 如果比对失败, 直接返回错误信息
      if(!code.equals(loginDto.getCode())){
          return R.error("验证码不正确");
      }
        //4). 如果比对成功, 需要根据手机号查询当前用户, 如果用户不存在, 则自动注册一个新用户
       LambdaQueryWrapper<User> wapper = new LambdaQueryWrapper<>();
        wapper.eq(User::getPhone,loginDto.getPhone());
        User user = userService.getOne(wapper);
        if(user==null){
            user=new User();
            user.setPhone(loginDto.getPhone());
            userService.save(user);
        }
        //5). 将登录用户的ID存储Session中
        session.setAttribute("user",user.getId());
        redisTemplate.delete(Redisks.REDIS_CODE+loginDto.getPhone());
        return R.success("登陆成功");
    }
    @PostMapping("/loginout")
    public R loginout(HttpServletRequest req){
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
